# -*- coding:utf-8 -*-
from rest_framework import serializers
from users.models import AuthUser, CompanyInfo, CompanyWebsiteInfo, Person, Registry, CompanyPerson, Records, \
    CompanyAutoSubmit, AdminRole, RoleBusinessPermission, Organization, OrganizationElevatorRelation, \
    AuthUserElevatorRelation, SystemLog
from basic.models import ElevatorInfo, ElevatorPersonInfo
import json
from ElevatorAdmin.settings import SUBMIT


class AuthUserSerializer(serializers.ModelSerializer):
    company_id = serializers.SerializerMethodField()
    company_name = serializers.SerializerMethodField()

    class Meta:
        model = AuthUser
        fields = ('id', 'username', 'phone', 'is_active', 'image', 'password', 'company_id', 'role', 'company_name',
                  "department", "gender", 'admin_role', 'desc', 'real_name', 'date_joined', 'permissions', 'email',
                  'admin_role_name', "permission_type", "elevators", "permit_all", "service_id"
                  )

    def get_company_id(self, obj):
        # cid = obj.service_id
        # try:
        #     return CompanyInfo.objects.get(id=cid).id
        # except:
        #     return None
        return obj.service_id

    def get_company_name(self, obj):
        cid = obj.service_id
        try:
            return CompanyInfo.objects.get(id=cid).name
        except:
            return None


class AuthUserListSerializer(serializers.ModelSerializer):
    company_id = serializers.SerializerMethodField()
    company_name = serializers.SerializerMethodField()
    card_id = serializers.SerializerMethodField()
    t1_card_no = serializers.SerializerMethodField()
    t1_card_file = serializers.SerializerMethodField()
    t1_end_time = serializers.SerializerMethodField()
    t2_card_no = serializers.SerializerMethodField()
    t2_card_file = serializers.SerializerMethodField()
    t2_end_time = serializers.SerializerMethodField()
    contract_start_time = serializers.SerializerMethodField()
    contract_end_time = serializers.SerializerMethodField()
    status = serializers.SerializerMethodField()
    contract_file = serializers.SerializerMethodField()
    social_security = serializers.SerializerMethodField()
    home_addr = serializers.SerializerMethodField()

    class Meta:
        model = AuthUser
        fields = ('id', 'username', 'phone', 'is_active', 'image', 'password', 'company_id', 'role', 'company_name',
                  "department", "gender", 'admin_role', 'desc', 'real_name', 'date_joined', 'permissions', 'email',
                  'admin_role_name', "permission_type", "elevators", "permit_all",
                  'card_id', 't1_card_no', 't1_card_file', 't1_end_time', 't2_card_no', "is_admin",
                  't2_card_file', 't2_end_time', 'contract_start_time', 'contract_end_time', 'status',
                  'contract_file', 'social_security', 'home_addr', 'update_by_user', 'registers')

    def get_company_id(self, obj):
        try:
            if obj.role == 0:
                return 0
            elif obj.role == 10:
                return obj.service_id
            else:
                return obj.company_person.company.id

        except:
            return None

    def get_company_name(self, obj):
        try:
            return CompanyInfo.objects.get(id=self.get_company_id(obj)).name
        except:
            return None
    def get_card_id(self, obj):
        try:
            return obj.person.card_id
        except:
            return None
    def get_t1_card_no(self, obj):
        try:
            return obj.person.t1_card_no
        except:
            return None
    def get_t1_card_file(self, obj):
        try:
            if obj.person.t1_card_file:
                return obj.person.t1_card_file.split(",")
            else:
                return []
        except:
            return []
    def get_t1_end_time(self, obj):
        try:
            return obj.person.t1_end_time
        except:
            return None
    def get_t2_card_no(self, obj):
        try:
            return obj.person.t2_card_no
        except:
            return None
    def get_t2_card_file(self, obj):
        try:
            if obj.person.t2_card_file:
                return obj.person.t2_card_file.split(",")
            else:
                return []
        except:
            return []
    def get_t2_end_time(self, obj):
        try:
            return obj.person.t2_end_time
        except:
            return None
    def get_contract_start_time(self, obj):
        try:
            return obj.person.contract_start_time
        except:
            return None
    def get_contract_end_time(self, obj):
        try:
            return obj.person.contract_end_time
        except:
            return None
    def get_status(self, obj):
        try:
            return obj.person.status
        except:
            return None
    def get_contract_file(self, obj):
        try:
            return json.loads(obj.person.contract_file)

            # return obj.person.contract_file
        except:
            return None
    def get_social_security(self, obj):
        try:
            return obj.person.social_security
        except:
            return None
    def get_home_addr(self, obj):
        try:
            return obj.person.home_addr
        except:
            return None


class AppPropertyAuthUserSerializer(serializers.ModelSerializer):

    class Meta:
        model = AuthUser
        fields = ("image", "sign_image", "password")


class AppAuthUserSerializer(serializers.ModelSerializer):
    company = serializers.SerializerMethodField()
    card_id = serializers.SerializerMethodField()
    home_addr = serializers.SerializerMethodField()
    person_id = serializers.SerializerMethodField()

    class Meta:
        model = AuthUser
        fields = ('id', 'username', 'phone', 'is_active', 'image', 'company', 'role', 'real_name', 'card_id',
                  'home_addr', 'sign_image', 'person_id')

    def get_company(self, obj):
        try:
            return obj.person.company.name
        except:
            return None

    def get_card_id(self, obj):
        try:
            return obj.person.card_id
        except:
            return None

    def get_home_addr(self, obj):
        try:
            return obj.person.home_addr
        except:
            return None

    def get_person_id(self, obj):
        try:
            return obj.person.id
        except:
            return None


class PersonSerializer(serializers.ModelSerializer):

    class Meta:
        model = Person
        fields = ('id', 'auth_user', 'card_id', 't1_card_no', 't1_card_file', 't1_end_time', 't2_card_no',
                  't2_card_file', 't2_end_time', 'contract_start_time', 'contract_end_time', 'company', 'status',
                  'contract_file', 'social_security', 'update_by', 'service_id', 'home_addr')


class CompanyPersonSerializer(serializers.ModelSerializer):

    class Meta:
        model = CompanyPerson
        fields = ('id', 'person_type', 'company', 'auth_user', 'service_id', 'is_admin')


class CompanyPersonListSerializer(serializers.ModelSerializer):
    username = serializers.SerializerMethodField()
    company_name = serializers.SerializerMethodField()
    real_name = serializers.SerializerMethodField()
    phone = serializers.SerializerMethodField()
    date_joined = serializers.SerializerMethodField()
    sign_image = serializers.SerializerMethodField()

    class Meta:
        model = CompanyPerson
        fields = ('id', 'company_id', 'username', 'company_name', 'real_name', 'phone', 'date_joined', 'is_admin',
                  'sign_image')

    def get_username(self, obj):
        return obj.auth_user.username

    def get_sign_image(self, obj):
        return obj.auth_user.sign_image

    def get_company_name(self, obj):
        return obj.company.name

    def get_phone(self, obj):
        return obj.auth_user.phone

    def get_real_name(self, obj):
        return obj.auth_user.real_name

    def get_date_joined(self, obj):
        return obj.auth_user.date_joined.strftime("%Y/%m/%d %H:%m:%S")


class AppPersonSerializer(serializers.ModelSerializer):

    class Meta:
        model = Person
        fields = ('id', 'auth_user', 'card_id', 't1_card_no', 't1_card_file', 't1_end_time', 't2_card_no',
                  't2_card_file', 't2_end_time', 'contract_start_time', 'contract_end_time', 'company', 'status',
                  'contract_file', 'social_security', 'update_by', 'home_addr')


class AppPersonListSerializer(serializers.ModelSerializer):
    username = serializers.SerializerMethodField()
    real_name = serializers.SerializerMethodField()
    phone = serializers.SerializerMethodField()
    update_by_people = serializers.SerializerMethodField()
    company_name = serializers.SerializerMethodField()

    class Meta:
        model = Person
        fields = ('id', 'auth_user', 'company', 'card_id', 'real_name', 'username', 'phone', 't1_card_no',
                  't1_end_time', 't2_card_no', 't2_end_time', 'contract_start_time', 'contract_end_time',
                  'status', 'company_name', 'update_by_people', 'update_time', 'contract_file', 'social_security',
                  't1_card_file', 't2_card_file', 'qr_code', 'home_addr')

    def get_username(self, obj):
        return obj.auth_user.username if obj.auth_user else None

    def get_real_name(self, obj):
        return obj.auth_user.real_name if obj.auth_user else None

    def get_phone(self, obj):
        return obj.auth_user.phone if obj.auth_user else None

    def get_company_name(self, obj):
        return obj.company.name if obj.company else None

    def get_update_by_people(self, obj):
        if obj.update_by:
            auth_user = AuthUser.objects.get(id=obj.update_by)
            if auth_user:
                return auth_user.username
        return None


class PersonListSerializer(serializers.ModelSerializer):
    username = serializers.SerializerMethodField()
    real_name = serializers.SerializerMethodField()
    phone = serializers.SerializerMethodField()
    update_by_people = serializers.SerializerMethodField()
    company_name = serializers.SerializerMethodField()
    # status = serializers.CharField(source='get_status_display')
    # image = serializers.SerializerMethodField()
    contract_file = serializers.SerializerMethodField()
    record = serializers.SerializerMethodField()
    sign_image = serializers.SerializerMethodField()

    class Meta:
        model = Person
        fields = ('id', 'auth_user', 'company', 'card_id', 'real_name', 'username', 'phone', 't1_card_no',
                  't1_end_time', 't2_card_no', 't2_end_time', 'contract_start_time', 'contract_end_time',
                  'status', 'company_name', 'update_by_people', 'update_time', 'contract_file', 'social_security',
                  't1_card_file', 't2_card_file', 'home_addr', 'record', 'registry_status', 'sign_image')

    def get_username(self, obj):
        return obj.auth_user.username if obj.auth_user else None

    def get_sign_image(self, obj):
        return obj.auth_user.sign_image

    def get_real_name(self, obj):
        return obj.auth_user.real_name if obj.auth_user else None

    def get_phone(self, obj):
        return obj.auth_user.phone if obj.auth_user else None

    def get_company_name(self, obj):
        return obj.company.name if obj.company else None

    def get_contract_file(self, obj):
        contract_file = json.loads(obj.contract_file) if obj.contract_file else None
        return contract_file

    def get_update_by_people(self, obj):
        if obj.update_by:
            auth_user = AuthUser.objects.get(id=obj.update_by)
            if auth_user:
                return auth_user.username
        return None

    def get_record(self, obj):
        request = self.context.get("request", None)
        role = request.user.role
        registry = Registry.objects.filter(type_for_reg=obj.__class__.__name__, reg_obj_id=obj.id).last()
        record = {
            "start_time": u"",
            "end_time": u"",
            "status": u"",
            "msg": u"",
            "data": u"",
            "reg_info": u"",
            "ret_info": u""
        }
        if registry:
            if role == 0 and registry.reg_info:
                reg_info = json.loads(registry.reg_info)
            else:
                reg_info = u""
            if role == 0 and registry.ret_info:
                ret_info = json.loads(registry.ret_info)
            else:
                ret_info = u""
            record.update({
                "start_time": registry.start_time.strftime("%Y-%m-%d %H:%M:%S"),
                "end_time": registry.end_time.strftime("%Y-%m-%d %H:%M:%S"),
                "rec_status": registry.status,
                "msg": registry.msg,
                "data": registry.data,
                "reg_info": reg_info,
                "ret_info": ret_info
            })
        return record
    # def get_image(self, obj):
        # return obj.auth_user.image if obj.auth_user else None


class PersonBindListSerializer(serializers.ModelSerializer):
    real_name = serializers.SerializerMethodField()

    class Meta:
        model = Person
        fields = ('id', 'real_name')

    def get_real_name(self, obj):
        return obj.auth_user.real_name


class CompanySerializer(serializers.ModelSerializer):

    class Meta:
        model = CompanyInfo
        fields = ('id', 'create_time', 'is_active', 'update_time', 'update_by', 'company_type', 'name', 'title',
                  'company_telephone', 'register_address', 'person_in_charge', 'person_in_charge_phone', 'create_by',
                  'business_lic', 'legal_person', 'legal_phone', 'lic_pic', 'unified_code', 'register_province',
                  'register_city', 'register_county', 'register_street', 'link_account', 'link_token', "address", "telephone")


class CompanyListSerializer(serializers.ModelSerializer):
    update_by_people = serializers.SerializerMethodField()
    # pwd = serializers.SerializerMethodField()
    # checkPass = serializers.SerializerMethodField()
    website = serializers.SerializerMethodField()
    register_info = serializers.SerializerMethodField()
    record = serializers.SerializerMethodField()
    elevator_num = serializers.SerializerMethodField()
    elevator_count = serializers.SerializerMethodField()
    admin_username = serializers.SerializerMethodField()
    auto_submit = serializers.SerializerMethodField()
    submit_display = serializers.SerializerMethodField()

    class Meta:
        model = CompanyInfo
        fields = ('id', 'name', 'update_by_people', 'update_time', 'company_type', 'admin_username',
                  'company_telephone', 'person_in_charge', 'person_in_charge_phone', 'register_province',
                  'register_city', 'register_county', 'register_street', 'register_address', 'unified_code',
                  'legal_person', 'legal_phone', 'website', 'register_info', 'business_lic', 'lic_pic',
                  'link_account', 'link_token', 'record', 'elevator_num', 'elevator_count', 'registry_status',
                  "auto_submit", "submit_display", "address", "telephone", 'title', "create_time", 'create_user')

    def get_submit_display(self, obj):
        return SUBMIT

    def get_register_info(self, obj):
        from ElevatorAdmin.settings import website
        province_name = ''
        city_name = ''
        county_name = ''
        street_name = ''
        for province in website:
            if province['address_code'] == obj.register_province:
                province_name = province['name']
            for city in province['children']:
                if city['address_code'] == obj.register_city:
                    city_name = city['name']
                for county in city['children']:
                    if county['address_code'] == obj.register_county:
                        county_name = county['name']
                    for street in county['children']:
                        if street['address_code'] == obj.register_street:
                            street_name = street['name']
        register_info = {
            "province_name": province_name,
            "city_name": city_name,
            "county_name": county_name,
            "street_name": street_name
        }
        return register_info

    def get_elevator_num(self, obj):
        com_id = obj.id
        elevator_qs = ElevatorInfo.objects.filter_active(maintain_company=com_id)
        if elevator_qs:
            elevator_num = elevator_qs.count()
            return elevator_num
        else:
            return None

    def get_elevator_count(self, obj):
        com_id = obj.id
        elevator_qs = ElevatorInfo.objects.filter_active(property_company=com_id)
        if elevator_qs:
            elevator_count = elevator_qs.count()
            return elevator_count
        else:
            return None

    # def get_username(self, obj):
    #     if obj.auth_user:
    #         return obj.auth_user.username
    #     else:
    #         return None

    def get_update_by_people(self, obj):
        if obj.update_by:
            auth_user = AuthUser.objects.get(id=obj.update_by)
            if auth_user:
                return auth_user.username
        return None

    def get_record(self, obj):
        registry = Registry.objects.filter(type_for_reg=obj.__class__.__name__, reg_obj_id=obj.id).last()
        record = {
            "start_time": u"",
            "end_time": u"",
            "status": u"",
            "msg": u"",
            "data": u"",
            "ret_info": u"",
            "reg_info": u""
        }
        if registry:
            request = self.context.get("request", None)
            role = request.user.role
            if role == 0 and registry.reg_info:
                reg_info = json.loads(registry.reg_info)
            else:
                reg_info = u""

            if role == 0 and registry.ret_info:
                ret_info = json.loads(registry.ret_info)
            else:
                ret_info = u""
            record.update({
                "start_time": registry.start_time.strftime("%Y-%m-%d %H:%M:%S"),
                "end_time": registry.end_time.strftime("%Y-%m-%d %H:%M:%S"),
                "rec_status": registry.status,
                "msg": registry.msg,
                "data": registry.data,
                "reg_info": reg_info,
                "ret_info": ret_info,
            })
        return record
    # def get_pwd(self, obj):
    #     return u""
    #
    # def get_checkPass(self, obj):
    #     return u""
    #
    # def get_address_info(self, obj):
    #     if obj.province and obj.city and obj.country:
    #         info = obj.province + u'/' + obj.city + u'/' + obj.country
    #         return info
    #     return None

    def get_website(self, obj):
        from ElevatorAdmin.settings import website as wb
        website_info = CompanyWebsiteInfo.objects.filter_active(company=obj.id).first()
        website = {
            "office_address": u"",
            "province_code": u"",
            "province_num": u"",
            "city_code": u"",
            "city_num": u"",
            "county_num": u"",
            "county_code": u"",
            "street_num": u"",
            "street_code": u"",
            "emergency_phone": u"",
            "office_main_person": u"",
            "office_main_person_phone": u""
        }
        if website_info:
            website["office_address"] = website_info.office_address
            website["province_num"] = website_info.province_code
            website["county_num"] = website_info.county_code
            website["street_num"] = website_info.street_code
            website["city_num"] = website_info.city_code
            website["emergency_phone"] = website_info.emergency_phone
            website["office_main_person"] = website_info.office_main_person
            website["office_main_person_phone"] = website_info.office_main_person_phone
            for province in wb:
                if province['address_code'] == website_info.province_code:
                    website["province_code"] = province['name']
                    province_obj = province
                    for city in province_obj['children']:
                        if city['address_code'] == website_info.city_code:
                            website["city_code"] = city['name']
                            city_obj = city
                            for county in city_obj['children']:
                                if county['address_code'] == website_info.county_code:
                                    website["county_code"] = county['name']
                                    county_obj = county
                                    for street in county_obj['children']:
                                        if street['address_code'] == website_info.street_code:
                                            website["street_code"] = street['name']

        return website

    def get_admin_username(self, obj):
        c_p = obj.company_person.filter_active(is_admin=True).first()
        if not c_p:
            return u""
        return c_p.auth_user.username

    def get_auto_submit(self, obj):
        cas = CompanyAutoSubmit.objects.filter_active(company=obj).first()
        if not cas:
            return True
        return cas.auto_submit


class CompanyListSerializerV2(serializers.ModelSerializer):
    label = serializers.SerializerMethodField()
    elevator_info = serializers.SerializerMethodField()

    class Meta:
        model = CompanyInfo
        fields = ('id', 'name', 'label', 'elevator_info', "address", "telephone")

    def get_label(self, obj):
        return obj.name

    def get_elevator_info(self, obj):
        request = self.context.get("request", None)
        user = request.user
        elevator_info = list()
        # maintain_company_id = user.company_person.company.id

        # property_company_id = obj.id
        e_qs = ElevatorInfo.objects.filter_active(property_company=obj.id, registry_status=20, is_binded=20)
        for obj in e_qs:
            if not obj.contract:
                continue
            elevator_dic = {}
            maintain_person = []
            elevator_type_choice = {}

            elevator_dic['elevator_id'] = obj.id
            elevator_dic['register_code'] = obj.register_code
            elevator_dic['internal_no'] = obj.internal_no

            elevator_type = obj.elevator_type
            if elevator_type == 10:
                elevator_type_choice['elevator_type_item'] = u'国标-曳引电梯-半月'
                elevator_type_choice['maintain_type'] = 190
            elif elevator_type == 20:
                elevator_type_choice['elevator_type_item'] = u'国标-液压电梯-半月'
                elevator_type_choice['maintain_type'] = 110
            elif elevator_type == 30:
                elevator_type_choice['elevator_type_item'] = u'国标-杂物电梯-半月'
                elevator_type_choice['maintain_type'] = 150
            elif elevator_type == 40:
                elevator_type_choice['elevator_type_item'] = u'国标-自动扶梯-半月'
                elevator_type_choice['maintain_type'] = 230
            elevator_dic['maintain_type'] = elevator_type_choice

            person_qs = ElevatorPersonInfo.objects.filter(elevator=obj.id, worker_type=10)
            for e_p in person_qs:
                maintain_person.append({"person_id": e_p.worker.id,
                                        "person_name": e_p.worker.auth_user.real_name})

            elevator_dic['maintain_person'] = maintain_person
            elevator_info.append(elevator_dic)
        return elevator_info


class RecordsListSerializer(serializers.ModelSerializer):
    time = serializers.SerializerMethodField()
    day = serializers.SerializerMethodField()

    class Meta:
        model = Records
        fields = ("id", "user_agent", "path", "ip", "time", "user_id", "is_anonymous", "parameters", "method", "day")

    def get_time(self, obj):
        return obj.request_time.strftime("%Y-%m-%d %H:%m:%S")

    def get_day(self, obj):
        return obj.request_time.strftime("%Y-%m-%d") if obj.request_time else u""


class AdminRoleSerializer(serializers.ModelSerializer):

    can_be_modify = serializers.SerializerMethodField()

    class Meta:
        model = AdminRole
        fields = ("id", "role_name", "role_desc", "role_type", "service_id", "company", "permissions", "can_be_modify",
                  "register_codes", "management_type", "management", "create_name", "create_time", "create_for_all")

    def get_can_be_modify(self, obj):
        request = self.context.get("request", None)
        user = request.user
        return obj.create_by == user


class RoleBusinessPermissionSerializer(serializers.ModelSerializer):

    class Meta:
        model = RoleBusinessPermission
        fields = ("id", "admin_role", "permission", "service_id")


class OrganizationSerializer(serializers.ModelSerializer):

    class Meta:
        model = Organization
        fields = ("id", "company", "parent_name", "parent", "service_id", "serial_num", "depth_id", "name", "list")


class OrganizationElevatorRelationSerializer(serializers.ModelSerializer):

    class Meta:
        model = OrganizationElevatorRelation
        fields = ("id", "organization", "register_code", "internal_no", "maintain_company_name",
                  "property_company_name", "service_id")


class ElevatorSerializer(serializers.ModelSerializer):
    class Meta:
        model = ElevatorInfo
        fields = ("id", "register_code", "internal_no", "maintain_company_name",
                  "property_company_name", "supervised")


class AuthUserElevatorRelationSerializer(serializers.ModelSerializer):

    class Meta:
        model = AuthUserElevatorRelation
        fields = ("id", "register_code", "internal_no", "maintain_company_name",
                  "property_company_name")


class CompanyForAuthUserSerializer(serializers.ModelSerializer):

    class Meta:
        model = CompanyInfo
        fields = ("id", "name")


class SystemLogSerializer(serializers.ModelSerializer):

    class Meta:
        model = SystemLog
        fields = ("id", "create_time", "create_by", "log")

































